Strict

Import xhrhtml5
Import mojo

Function Main:Int()
    New MyDemoApp()
	Return 0
End

Class MyDemoApp Extends App

	Const GET_URL:String = "http://localhost:51269/api/values/5/fdf"
	Const POST_URL:String = "http://localhost:51269/api/values"
	Const DEFAULT_TIMEOUT:Int = 3000

	Field request:XhrObject = Null
	Field stream:JsonStream = Null
	Field value:Int = 0
	Field count:Int = 2				' Used to prioritize the requests.
	
	Method OnCreate:Int()
		
		' Create the Xhr object.
		request = New XhrTesting()

		' Send a GET request to an URL.
		request.Get(GET_URL, DEFAULT_TIMEOUT)
		
		' Send a POST request to anU URL.
		request.Post(POST_URL, "testa:aaa,testb:bbb", DEFAULT_TIMEOUT)
		
		SetUpdateRate(60)
		
		Return 0
	End

	Method OnUpdate:Int()

			#rem *** Tests of the JsonStream class. You can remove this bloc. ***
			' Transform the response from JSON to an actual test object.
			stream = New JsonStream()

			stream.WriteJson(get.GetResult())
			Local obj:= stream.ReadObject()
			Local t:Testing = Testing(obj)
			
			Print(t.message)
			Print(t.id)
			#end
	
		Return 0
	End
	
	Method OnRender:Int()
		Cls
		Return 0
	End
	
	Method OnSuspend:Int()
		Return 0
	End
	
	Method OnResume:Int()
		Return 0
	End
End

' You can create your own object based on the XhrObject and override the events or simply use
' the properties (like the status) associated to the XhrObject to see the state of the request.

' Here the lsit of available events :
' OnRequestError:Void()
' OnRequestSuccess:Void(response:String)
' OnRequestReceived:Void()
' OnRequestProcessing:Void()
' OnRequestComplete:Void()
' OnConnectionEstablished:Void()
' OnRequestTimeout:Void()

Class XhrTesting Extends XhrObject
	Method OnRequestError:Void()
		Print("Request failure: " + Self.GetServerStatusCode() + ", " + Self.GetStatus() + ", " + Self.GetMessage())
		Self.Reset()
	End
	Method OnRequestSuccess:Void(response:String)
		Print("Request Success: " + Self.GetServerStatusCode() + ", " + Self.GetStatus() + ", " + Self.GetMessage())
		Print("Response: " + response)
		Self.Reset()
	End
End